<template>
  <!-- 科研人才足迹圈 -->
  <div>
    <div id="chartThree"></div>
  </div>
</template>

<script>
// import chinaJson from "echarts/map/json/china.json"
import chinaJson from "@/utils/mock/china.json";
import chinaJson2 from "@/utils/mock/china.json";
import worldJson from "echarts/map/json/world.json";
import { world } from "@/utils/mock/world";
import { transCNCountry, resize } from "@/utils/utils";
import { geoCoord } from "@/utils/mock/geoCoordMap";
export default {
  mixins: [resize],
  props: {
    info: {
      type: Object,
    },
  },
  data() {
    return {
      chartThree: null,
      data: [],
    };
  },
  methods: {
    init() {
      this.$echarts.registerMap("china", chinaJson);
      this.$post(this.$Url.team.talentsRecord, {
        musts: {
          date_sort: "1",
          "in2id.id": this.info.key,
        },
        aggs: [
          {
            type: "base",
            size: "50",
            field: "an",
            subAggs: [
              {
                type: "min",
                field: "ad",
              },
              {
                type: "max",
                field: "ad",
              },
              {
                size: "1",
                type: "base",
                field: "province",
              },
              {
                size: "1",
                type: "base",
                field: "pn",
              },
            ],
          },
        ],
      })
        .then((res) => {
          let data = res.data;
          let newData = [];
          let ths = this;
          for (let i in data) {
            data[i].name = data[i].city; // .replace(/市|省|自治区|壮族自治区|维吾尔|回族自治区/g, '')
            let from = data[i];
            let to = data[Number(i) + 1] || { name: "" };
            if (to.name !== "") {
              newData.push([from, to]);
            }
          }

          // 测试
          // newData.push([{name: '江苏省'}, {name: '辽宁省'}])
          this.data = newData;

          var convertData = function(data) {
            let res = [];
            for (let i in data) {
              let dataItem = data[i];
              let fromCoord =
                (dataItem[0] && ths.getGeoCoord(dataItem[0].name)) || [];
              let toCoord =
                (dataItem[1] && ths.getGeoCoord(dataItem[1].name)) || [];
              if (fromCoord.length > 0 && toCoord.length > 0) {
                res.push({
                  fromName: dataItem[0].name,
                  toName: dataItem[1].name,
                  coords: [fromCoord, toCoord],
                  value: dataItem[1].doc_count,
                  visualMap: false,
                });
              }
            }
            return res;
          };

          var series = [];
          let that = this;
          let n = 1;

          // 为了让第一个点在初始化出现，所以需要拼接[{name: ''}, {name: '北京市'}]这种数据
          let startData = JSON.parse(JSON.stringify(this.data));
          let start = [[{ name: "" }, startData[0][0]], startData[0]];
          // 如果第一个节点是重复的，即都在同一个地区，则就不展示第一个节点的label了
          if (startData[0][0].city === startData[0][1].city) {
            start = [startData[0]];
          }
          fn(start);
          timer();
          function timer() {
            that.inter = setInterval(() => {
              n++;
              if (n > that.data.length) {
                setTimeout(() => {
                  clearInterval(that.inter);
                  that.inter = null;
                  that.chartThree.clear();
                  n = 1;
                  series = [];
                  fn(start);
                  timer();
                }, 3000);
              } else {
                let arr = ths.data.slice(n - 1, n);
                fn(arr);
              }
            }, 3000);
          }

          function fn(arr) {
            let newArr = [arr];
            newArr.forEach((item, i) => {
              series.push(
                {
                  type: "lines",
                  zlevel: 2,
                  animation: false,
                  tooltip: {
                    show: false,
                  },
                  effect: {
                    show: true,
                    period: 3, //箭头指向速度，值越小速度越快
                    trailLength: 0, //特效尾迹长度[0,1]值越大，尾迹越长重
                    symbol: "arrow", //箭头图标
                    symbolSize: 8, //图标大小
                    color: "241c75",
                    loop: false,
                  },
                  lineStyle: {
                    // color: "white",
                    normal: {
                      color: "#241c75",
                      width: 1,
                      opacity: 0.2,
                      curveness: 0.1, // 边的弧度
                    },
                  },
                  data: convertData(item),
                },
                {
                  type: "effectScatter",
                  coordinateSystem: "geo",
                  zlevel: 2,
                  animation: false,
                  tooltip: {
                    show: false,
                  },
                  rippleEffect: {
                    //涟漪特效
                    color: "#cecfe4",
                    period: 3, //动画时间，值越小速度越快
                    brushType: "fill", //波纹绘制方式 stroke, fill
                    scale: 2, //波纹圆环最大限制，值越大波纹越大
                  },
                  symbol: "circle",
                  symbolSize: function(val) {
                    return 13; //圆环大小
                  },
                  label: {
                    normal: {
                      show: true,
                      position: "top",
                      backgroundColor: "rgba(255, 255, 255, 0.6)",
                      borderRadius: 2,
                      formatter: (params) => {
                        let name = params.data.name;
                        let start =
                          (params.data.start &&
                            params.data.start.split("-")[0]) ||
                          "";
                        let end =
                          (params.data.end && params.data.end.split("-")[0]) ||
                          "";
                        // let start = params.data.start
                        // let end = params.data.end
                        let an = (params.data.an && params.data.an) || "暂无";
                        let str = "";
                        str +=
                          `{h4|${start}-${end}}\n` +
                          "{hr|}\n" +
                          "{hr15|}\n" +
                          `{a|任职地点：}{b|${name}}\n` +
                          "{hr5|}\n" +
                          `{a|任职机构：}{b|${an}}\n` +
                          "{hr15|}";
                        return str;
                      },
                      rich: {
                        h4: {
                          lineHeight: 30,
                          padding: 16,
                          borderBottom: "1px solid #000",
                          color: "#595959",
                        },
                        hr: {
                          width: "100%",
                          height: 0,
                          borderColor: "#f5f5fe",
                          borderWidth: 1,
                        },
                        hr5: {
                          width: "100%",
                          height: 5,
                        },
                        hr15: {
                          width: "100%",
                          height: 15,
                        },
                        a: {
                          lineHeight: 18,
                          padding: [0, 0, 0, 16],
                          fontSize: 14,
                          color: "#241c75",
                        },
                        b: {
                          lineHeight: 18,
                          padding: [0, 16, 0, 0],
                          fontWeight: "bold",
                          fontSize: 14,
                          color: "#241c75",
                        },
                      },
                      // position: "right", //显示位置
                      // offset: [5, 0], //偏移设置
                      // formatter: "{b}", //圆环显示文字
                    },
                    emphasis: {
                      show: true,
                    },
                  },
                  itemStyle: {
                    normal: {
                      color: "#504da5", //标志颜色
                      borderColor: "#fff",
                    },
                    emphasis: {
                      areaColor: "orange",
                    },
                  },
                  data: item.map(function(dataItem) {
                    if (dataItem[1].name !== "") {
                      // return dataItem[1]
                      return {
                        // name: dataItem[1].name,
                        value: ths
                          .getGeoCoord(dataItem[1].name)
                          .concat([dataItem[1].value]),
                        ...dataItem[1],
                        visualMap: false,
                      };
                    }
                  }),
                }
              );
            });

            for (let i in series) {
              if (series[i].type === "effectScatter") {
                let data = series[i].data;
                // 因为中间隔了一个lines，所以+2
                let nextData =
                  (series[Number(i) + 2] && series[Number(i) + 2].data) || [];
                for (let j in data) {
                  for (let k in nextData) {
                    if (
                      data[j]["city"] &&
                      data[j]["city"] === nextData[k]["city"]
                    ) {
                      series[i]["label"]["normal"]["show"] = false;
                    }
                  }
                }
              }
            }
            let option = {
              backgroundColor: "#fff",
              title: {
                text: "",
                left: "center",
                textStyle: {
                  color: "#fff",
                },
              },
              tooltip: {
                trigger: "item",
                backgroundColor: "#1540a1",
                borderColor: "#FFFFCC",
                showDelay: 0,
                hideDelay: 0,
                enterable: true,
                transitionDuration: 0,
                extraCssText: "z-index:100",
                formatter: function(params, ticket, callback) {
                  //根据业务自己拓展要显示的内容
                  var res = "";
                  var name = params.name;
                  var value = params.value[params.seriesIndex + 1];
                  res =
                    "<span style='color:#fff;'>" +
                    name +
                    "</span><br/>数据：" +
                    value;
                  return res;
                },
              },
              visualMap: {
                //图例值控制
                min: 0,
                max: 10000,
                show: false,
                calculable: true,
              },
              geo: {
                map: "china",
                label: {
                  emphasis: {
                    show: false,
                  },
                },
                roam: true, //是否允许缩放
                layoutCenter: ["50%", "66%"], //地图位置
                layoutSize: "130%",
                itemStyle: {
                  normal: {
                    areaColor: "#edf0f4",
                    borderColor: "#fff",
                  },
                  // emphasis: {
                  //     areaColor: '#edf0f4'
                  // }
                },
              },
              series: series,
            };
            that.chartThree.setOption(option);
          }
        })
        .catch((err) => {});
    },
    // 获取省市中心坐标
    getGeoCoord(name) {
      let geoCoord = [];
      let features = chinaJson2.features;
      for (let i in features) {
        let properties = features[i].properties;
        if (properties.name === name) {
          geoCoord = properties.centroid || properties.center;
          break;
        }
      }
      return geoCoord;
    },
  },
  mounted() {
    this.chartThree = this.$echarts.init(document.getElementById("chartThree"));
    this.init();
    // this.init2()
  },
};
</script>

<style lang="scss" scoped>
#chartThree {
  width: 100%;
  height: 360px;
}
</style>
